from flask import Blueprint, request, jsonify
from datetime import datetime
import logging
from ..utils import validate_user_id
from ..database import db_connection, mongo_collection
from ..config import Config
from ..models import User, Device, Admin, db
from bson.objectid import ObjectId
import random
from ..utils.ip_utils import get_client_ip

feedback_bp = Blueprint('feedback', __name__)
logger = logging.getLogger('FeedbackAPI')

@feedback_bp.route('/v1/submit', methods=['POST'])
def submit_feedback():
    """
    用户提交反馈接口
    请求示例：
    {
        "user_id": 4,
        "title": "声音放不出来",
        "content": "我的设备声音无法播放，已经重启多次，尝试重启设备无效",
        "type": "BUG",
        "phonenumber": "13800138000",
        "device_id": 1,
        "attachment_url": "https://example.com/screenshots/sound_issue.jpg"
    }
    """
    try:
        # 验证请求数据
        if not request.is_json:
            return jsonify(
                code=Config.ERROR_CODES['INVALID_JSON'][0],
                message=Config.ERROR_CODES['INVALID_JSON'][1]
            ), 400
            
        data = request.get_json()
        
        # 校验必要字段
        required_fields = ['user_id', 'title', 'content', 'type']
        if missing := [f for f in required_fields if f not in data]:
            logger.warning(f"缺少必要字段: {', '.join(missing)}")
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message=f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: {', '.join(missing)}"
            ), 400
        
        user_id = data['user_id']
        title = data['title']
        content = data['content']
        feedback_type = data['type']
        
        # 验证user_id有效性
        if not validate_user_id(str(user_id)):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
            
        # 验证反馈类型
        valid_types = ['BUG', '建议', '投诉']
        if feedback_type not in valid_types:
            return jsonify(
                code=40016,
                message=f"无效的反馈类型，有效值为: {', '.join(valid_types)}"
            ), 400
        
        # 随机分配给一个活跃的管理员（排除1级管理员）
        active_admins = Admin.query.filter(
            Admin.is_active == True,
            Admin.admin_level != 1
        ).all()
        assigned_admin = None
        
        if active_admins:
            assigned_admin = random.choice(active_admins)
            admin_id = assigned_admin.admin_id
            admin_name = assigned_admin.admin_name
        else:
            # 如果没有符合条件的管理员，使用默认值
            admin_id = None
            admin_name = "未分配"
        
        # 准备存储数据
        now = datetime.now()
        feedback_data = {
            "user_id": int(user_id),
            "title": title,
            "content": content,
            "type": feedback_type,
            "status": "未处理",
            "submit_time": now,
            "device_id": data.get('device_id'),
            "phonenumber": data.get('phonenumber'),
            "attachment_url": data.get('attachment_url'),
            "satisfaction": None,
            "assigned_admin_id": admin_id,
            "assigned_admin_name": admin_name,
            "assign_time": now if admin_id else None,
            "last_update_time": now
        }
        
        # 存储到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            # 获取当前最大反馈ID
            last_feedback = collection.find_one(sort=[("feedback_id", -1)])
            new_id = 1 if not last_feedback else last_feedback.get("feedback_id", 0) + 1
            
            # 添加新ID到反馈数据
            feedback_data["feedback_id"] = new_id
            
            result = collection.insert_one(feedback_data)
            
            if not result.inserted_id:
                logger.error("反馈提交失败")
                return jsonify({
                    "code": 50003,
                    "message": "数据库操作失败"
                }), 500
                
            logger.info(f"用户反馈提交成功 用户:{user_id} 反馈ID:{new_id} 分配给管理员:{admin_name}")
            
            # 记录管理员操作日志
            with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as admin_log:
                admin_log.insert_one({
                    "admin_id": None,  # 此处不是管理员操作
                    "admin_name": "系统",
                    "operation": "user_submit_feedback",
                    "timestamp": datetime.now(),
                    "ip": get_client_ip(),
                    "path": request.path,
                    "method": request.method,
                    "status": "success",
                    "details": {
                        "feedback_id": new_id,
                        "user_id": user_id,
                        "device_id": data.get('device_id'),
                        "feedback_type": feedback_type
                    }
                })
            
            return jsonify({
                "code": 0,
                "message": "反馈提交成功",
                "feedback_id": new_id,
                "assigned_admin": admin_name
            }), 201

    except Exception as e:
        logger.exception(f"提交反馈异常: {str(e)}")
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@feedback_bp.route('/v1/list', methods=['GET'])
def list_feedback():
    """
    获取用户反馈列表接口
    请求示例：/api/v1/feedback/list?user_id=4&status=未处理&page=1&page_size=10
    
    参数说明：
    - user_id: 用户ID (必填)
    - status: 状态筛选 (可选)
    - type: 类型筛选 (可选)
    - page: 页码，默认1
    - page_size: 每页数量，默认10
    """
    try:
        # 获取查询参数
        user_id = request.args.get('user_id')
        status = request.args.get('status')
        feedback_type = request.args.get('type')
        
        # 获取分页参数
        try:
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('page_size', 10))
            if page < 1 or page_size < 1:
                return jsonify(
                    code=40010,
                    message="页码和每页数量必须为正整数"
                ), 400
        except ValueError:
            return jsonify(
                code=40010,
                message="页码和每页数量必须为整数"
            ), 400
        
        # 参数验证
        if not user_id:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message="缺少必要参数: user_id"
            ), 400
            
        if not validate_user_id(user_id):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
        
        # 构建查询条件
        query = {"user_id": int(user_id)}
        if status:
            valid_status = ['未处理', '处理中', '已回复']
            if status not in valid_status:
                return jsonify(
                    code=40016,
                    message=f"无效的状态值，有效值为: {', '.join(valid_status)}"
                ), 400
            query["status"] = status
            
        if feedback_type:
            valid_types = ['BUG', '建议', '投诉']
            if feedback_type not in valid_types:
                return jsonify(
                    code=40016,
                    message=f"无效的反馈类型，有效值为: {', '.join(valid_types)}"
                ), 400
            query["type"] = feedback_type
        
        # 从MongoDB获取反馈数据
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            # 获取总数
            total_count = collection.count_documents(query)
            
            # 计算总页数
            total_pages = (total_count + page_size - 1) // page_size if total_count > 0 else 1
            
            # 获取分页数据
            skip = (page - 1) * page_size
            feedback_list = list(collection.find(query).sort("submit_time", -1).skip(skip).limit(page_size))
            
            # 格式化数据
            result_list = []
            for item in feedback_list:
                result_list.append({
                    "feedback_id": item.get("feedback_id"),
                    "title": item["title"],
                    "content": item["content"],
                    "type": item["type"],
                    "status": item["status"],
                    "submit_time": item["submit_time"].isoformat() if isinstance(item["submit_time"], datetime) else item["submit_time"],
                    "attachment_url": item.get("attachment_url"),
                    "assigned_admin": item.get("assigned_admin_name", "未分配")
                })
            
            return jsonify({
                "code": 0,
                "message": "获取反馈列表成功",
                "total": total_count,
                "page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "feedback_list": result_list
            }), 200
                
    except Exception as e:
        logger.exception(f"获取反馈列表异常: {str(e)}")
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@feedback_bp.route('/v1/update_satisfaction', methods=['POST'])
def update_satisfaction():
    """
    更新反馈满意度接口
    请求示例：
    {
        "feedback_id": "60f7b0b9e6b3f87654321012",
        "user_id": 4,
        "satisfaction": 5
    }
    """
    try:
        # 验证请求数据
        if not request.is_json:
            return jsonify(
                code=Config.ERROR_CODES['INVALID_JSON'][0],
                message=Config.ERROR_CODES['INVALID_JSON'][1]
            ), 400
            
        data = request.get_json()
        
        # 校验必要字段
        required_fields = ['feedback_id', 'user_id', 'satisfaction']
        if missing := [f for f in required_fields if f not in data]:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message=f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: {', '.join(missing)}"
            ), 400
        
        feedback_id = data['feedback_id']
        user_id = data['user_id']
        satisfaction = data['satisfaction']
        
        # 验证user_id
        if not validate_user_id(str(user_id)):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
            
        # 验证satisfaction
        try:
            satisfaction = int(satisfaction)
            if not 1 <= satisfaction <= 5:
                return jsonify(
                    code=40008,
                    message="满意度必须是1-5之间的整数"
                ), 400
        except ValueError:
            return jsonify(
                code=40008,
                message="满意度必须是整数"
            ), 400
            
        # 验证feedback_id格式
        try:
            object_id = ObjectId(feedback_id)
        except:
            return jsonify(
                code=40009,
                message="无效的反馈ID格式"
            ), 400
        
        # 更新MongoDB中的满意度
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            # 先检查反馈是否存在且属于该用户
            feedback = collection.find_one({
                "_id": ObjectId(feedback_id),
                "user_id": int(user_id)
            })
            
            if not feedback:
                return jsonify({
                    "code": 40404,
                    "message": "未找到对应的反馈记录"
                }), 404
            
            # 更新满意度和最后更新时间
            now = datetime.now()
            result = collection.update_one(
                {"_id": ObjectId(feedback_id)},
                {"$set": {
                    "satisfaction": satisfaction,
                    "last_update_time": now
                }}
            )
            
            if result.modified_count > 0:
                logger.info(f"反馈满意度更新成功 反馈ID:{feedback_id} 满意度:{satisfaction}")
                return jsonify({
                    "code": 0,
                    "message": "反馈满意度更新成功"
                }), 200
            else:
                logger.warning(f"反馈满意度未更新 反馈ID:{feedback_id}")
                return jsonify({
                    "code": 40004,
                    "message": "反馈满意度未更新，可能已经是相同值"
                }), 400
                
    except Exception as e:
        logger.exception(f"更新反馈满意度异常: {str(e)}")
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@feedback_bp.route('/v1/detail', methods=['GET'])
def get_feedback_detail():
    """
    获取反馈回复详情接口
    请求示例：/api/feedback/v1/detail?user_id=4&feedback_id=4
    """
    try:
        # 获取参数
        user_id = request.args.get('user_id')
        feedback_id = request.args.get('feedback_id')
        
        # 参数验证
        if not user_id or not feedback_id:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message="缺少必要参数: user_id 或 feedback_id"
            ), 400
            
        if not validate_user_id(user_id):
            return jsonify(
                code=40007,
                message="无效的用户ID格式"
            ), 400
        
        # 获取回复信息
        replies = []
        with mongo_collection(Config.MONGODB_COLLECTIONS["feedback_replies"]) as reply_collection:
            # 检查 feedback_id 是否为数字
            try:
                feedback_id_int = int(feedback_id)
                query = {
                    "feedback_id": feedback_id_int,
                    "user_id": int(user_id)
                }
            except ValueError:
                # 如果不是数字，则保持原样
                query = {
                    "feedback_id": feedback_id,
                    "user_id": int(user_id)
                }
                
            logger.info(f"查询反馈回复，参数: {query}")
            reply_cursor = reply_collection.find(query).sort("reply_time", 1)
            
            for reply in reply_cursor:
                replies.append({
                    "reply_id": str(reply.get("_id", "")),
                    "content": reply["content"],
                    "reply_by": reply.get("reply_by", "客服"),
                    "reply_time": reply["reply_time"].isoformat() if isinstance(reply["reply_time"], datetime) else reply["reply_time"],
                    "admin_id": reply.get("admin_id"),
                    "admin_level": reply.get("admin_level")
                })
            
            # 记录找到的回复数量
            reply_count = len(replies)
            logger.info(f"反馈 {feedback_id} 找到 {reply_count} 条回复")
            if reply_count == 0:
                # 如果没有找到回复，尝试不带user_id查询一次，看是否有数据
                test_query = {"feedback_id": query["feedback_id"]}
                test_count = reply_collection.count_documents(test_query)
                logger.warning(f"反馈 {feedback_id} 未找到回复，不带用户ID的查询结果: {test_count} 条")
        
        return jsonify({
            "code": 0,
            "message": "获取反馈回复成功",
            "feedback_id": feedback_id,
            "user_id": int(user_id),
            "replies": replies,
            "reply_count": len(replies)
        }), 200
            
    except Exception as e:
        logger.exception(f"获取反馈回复异常: {str(e)}")
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@feedback_bp.route('/v1/reassign', methods=['POST'])
def reassign_feedback():
    """
    管理员重新分配反馈接口
    请求示例：
    {
        "feedback_id": "60f7b0b9e6b3f87654321012",
        "admin_id": 2,
        "new_admin_id": 3,
        "reason": "专业领域更匹配"
    }
    """
    try:
        # 验证请求数据
        if not request.is_json:
            return jsonify(
                code=Config.ERROR_CODES['INVALID_JSON'][0],
                message=Config.ERROR_CODES['INVALID_JSON'][1]
            ), 400
            
        data = request.get_json()
        
        # 校验必要字段
        required_fields = ['feedback_id', 'admin_id', 'new_admin_id']
        if missing := [f for f in required_fields if f not in data]:
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message=f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: {', '.join(missing)}"
            ), 400
        
        feedback_id = data['feedback_id']
        admin_id = data['admin_id']
        new_admin_id = data['new_admin_id']
        reason = data.get('reason', '未提供原因')
        
        # 验证feedback_id格式
        try:
            object_id = ObjectId(feedback_id)
        except:
            return jsonify(
                code=40009,
                message="无效的反馈ID格式"
            ), 400
        
        # 验证管理员ID
        try:
            admin_id = int(admin_id)
            new_admin_id = int(new_admin_id)
        except ValueError:
            return jsonify(
                code=40007,
                message="管理员ID必须是整数"
            ), 400
            
        # 验证新管理员是否存在且活跃
        new_admin = Admin.query.filter_by(admin_id=new_admin_id, is_active=True).first()
        if not new_admin:
            return jsonify(
                code=40404,
                message="指定的新管理员不存在或未激活"
            ), 404
            
        # 查找反馈并确认当前管理员有权限
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            feedback = collection.find_one({"_id": ObjectId(feedback_id)})
            
            if not feedback:
                return jsonify({
                    "code": 40404,
                    "message": "未找到对应的反馈记录"
                }), 404
                
            # 检查当前管理员是否有权限重新分配
            # 只有分配给自己的反馈或超级管理员才能重新分配
            current_admin = Admin.query.filter_by(admin_id=admin_id).first()
            if not current_admin:
                return jsonify({
                    "code": 40301,
                    "message": "管理员不存在"
                }), 403
                
            if feedback.get('assigned_admin_id') != admin_id and current_admin.admin_level < 2:
                return jsonify({
                    "code": 40301,
                    "message": "无权重新分配此反馈"
                }), 403
                
            # 更新分配信息
            now = datetime.now()
            result = collection.update_one(
                {"_id": ObjectId(feedback_id)},
                {"$set": {
                    "assigned_admin_id": new_admin_id,
                    "assigned_admin_name": new_admin.admin_name,
                    "last_update_time": now
                }}
            )
            
            if result.modified_count > 0:
                # 记录操作日志
                with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as admin_log:
                    admin_log.insert_one({
                        "admin_id": None,  # 此处不是管理员操作
                        "admin_name": "系统",
                        "operation": "user_reassign_feedback",
                        "timestamp": datetime.now(),
                        "ip": get_client_ip(),
                        "path": request.path,
                        "method": request.method,
                        "status": "success",
                        "details": {
                            "feedback_id": feedback_id,
                            "admin_id": admin_id,
                            "new_admin_id": new_admin_id,
                            "reason": reason
                        }
                    })
                
                logger.info(f"反馈重新分配成功 反馈ID:{feedback_id} 从管理员:{current_admin.admin_name} 到管理员:{new_admin.admin_name}")
                return jsonify({
                    "code": 0,
                    "message": "反馈重新分配成功",
                    "assigned_admin": new_admin.admin_name
                }), 200
            else:
                logger.warning(f"反馈重新分配未更新 反馈ID:{feedback_id}")
                return jsonify({
                    "code": 40004,
                    "message": "反馈重新分配未更新，可能已经分配给该管理员"
                }), 400
                
    except Exception as e:
        logger.exception(f"重新分配反馈异常: {str(e)}")
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500